<?php
/**
 * Created by PhpStorm.
 * User: lihao
 * Date: 2017/7/20
 * Time: 下午3:17
 */

class Photo extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Photo_model');
    }

    public function index()
    {
        $re = $this->Photo_model->getDirsWithCover();
        $this->load->view('photo', array('dirs'=>$re));
    }

    public function skim($name, $type) {
        $images = $this->Photo_model->getPhotots($type, null);
        $this->load->view('photoskim', array(
            'dir'=>$name,
            'picid'=>$type,
            'images'=>$images
        ));
    }


    public function createdir() {
        //处理跨域
        $dir = $_POST['dir'];
        $path = 'photos/'.$dir;
        $msg = "创建成功";
        $succ = 1;
        if (is_dir($path)) {
            $msg = "文件夹已存在";
            $succ = 0;
        } else {
            $res = mkdir($path, 0777, true);
            if ($res) {
                $result = $this->Photo_model->createDir($dir);
                if ($result) {
                    $msg = "创建成功";
                } else {
                    $msg = "插入数据库失败";
                    $succ = 0;
                }
            } else {
                $msg = "创建失败";
                $succ = 0;
            }
        }
        $this->echoJson('', $msg, $succ);
    }

    public function uploadImg($dir, $typeid) {
        $config['upload_path']      = urldecode('./photos/'.$dir);
        $config['allowed_types']    = 'gif|jpg|png';
        $config['max_size']     = 1024;
        $config['max_width']        = 2048;
        $config['max_height']       = 2048;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('userfile'))
        {
            $error = array('error' => $this->upload->display_errors());
            echo json_encode(array(
                'msg'=>$error
            ));
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());

            if ($data) {
                $fileName = $data['upload_data']['file_name'];
                $re = $this->Photo_model->saveImg($fileName, 1, $typeid);
                if ($re) {
                    echo json_encode(array(
                        'msg'=>"成功"
                    ));
                } else {
                    echo json_encode(array(
                        'msg'=>"失败"
                    ));
                }
            }
        }
    }


}